package com.milk.Dao;

import com.milk.DB.DBConnection;
import com.milk.entity.Orders;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrdersDao {
    // 查询所有订单信息
    public static List<Orders> findAll() {
        List<Orders> orders = new ArrayList<>();
        String sql = "SELECT * FROM orders";
        try (Connection connection = DBConnection.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql);
             ResultSet resultSet = statement.executeQuery()) {
            while (resultSet.next()) {
                Orders order = new Orders();
                order.setId(resultSet.getInt("id"));
                order.setUserName(resultSet.getString("user_name"));
                order.setContactPhone(resultSet.getString("contact_phone"));
                order.setOrderTime(resultSet.getTimestamp("order_time"));
                order.setStatus(resultSet.getString("status"));
                order.setDrinkIds(resultSet.getString("drink_ids"));
                orders.add(order);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return orders;
    }

    // 根据id查询订单信息
    public static Orders findById(int id) {
        Orders order = null;
        String sql = "SELECT * FROM orders WHERE id =?";
        try (Connection connection = DBConnection.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, id);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                order = new Orders();
                order.setId(resultSet.getInt("id"));
                order.setUserName(resultSet.getString("user_name"));
                order.setContactPhone(resultSet.getString("contact_phone"));
                order.setOrderTime(resultSet.getTimestamp("order_time"));
                order.setStatus(resultSet.getString("status"));
                order.setDrinkIds(resultSet.getString("drink_ids"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return order;
    }

    // 添加订单
    public static int add(Orders order) {
        String sql = "INSERT INTO orders (user_name, contact_phone, order_time, status, drink_ids) VALUES (?,?,?,?,?)";
        try (Connection connection = DBConnection.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, order.getUserName());
            statement.setString(2, order.getContactPhone());
            statement.setTimestamp(3, new java.sql.Timestamp(order.getOrderTime().getTime()));
            statement.setString(4, order.getStatus());
            statement.setString(5, order.getDrinkIds());
            return statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("添加订单失败", e);
        }
    }

    // 根据id删除订单
    public static int deleteById(int id) {
        String sql = "DELETE FROM orders WHERE id =?";
        try (Connection connection = DBConnection.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, id);
            return statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

    // 修改订单状态
    public static int updateStatus(int id, String newStatus) {
        // 确保 newStatus 不为空
        if (newStatus == null || newStatus.trim().isEmpty()) {
            throw new RuntimeException("订单状态不能为空");
        }

        String sql = "UPDATE orders SET status = ? WHERE id = ?";
        try (Connection connection = DBConnection.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, newStatus);
            statement.setInt(2, id);

            // 打印日志，检查 SQL 是否正确
            System.out.println("执行的 SQL: " + statement);

            return statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("修改订单状态失败", e);
        }
    }

    // 根据用户名模糊搜索订单信息（可根据更多条件扩展搜索功能）
    public static List<Orders> searchByUserName(String userName) {
        List<Orders> orders = new ArrayList<>();
        String sql = "SELECT * FROM orders WHERE user_name LIKE CONCAT('%',?, '%')";
        try (Connection connection = DBConnection.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, userName);
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Orders order = new Orders();
                order.setId(resultSet.getInt("id"));
                order.setUserName(resultSet.getString("user_name"));
                order.setContactPhone(resultSet.getString("contact_phone"));
                order.setOrderTime(resultSet.getTimestamp("order_time"));
                order.setStatus(resultSet.getString("status"));
                order.setDrinkIds(resultSet.getString("drink_ids"));
                orders.add(order);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return orders;
    }
}